<template>
	<div v-loading="loading" class="app-main-content-box">
		<!-- 标题 -->
		<div class="app-main-top-box">
			<div class="title">会员生日权益</div>
			<el-button size="medium" round @click="back">返回</el-button>
		</div>

		<!-- 表单 -->
		<div>
			<el-form ref="form" :model="form" :rules="rules" label-width="150px" label-suffix="：" size="small">
				<el-form-item label="会员生日折扣" prop="right.discount" :rules="rules.discount">
					<el-switch v-model="form.right.discount" active-color="#13ce66" inactive-color="#ff4949" />
					<el-collapse-transition>
						<div v-if="form.right.discount">
							<el-form-item v-for="(item, index) in form.categories" :key="item.categoryId" :prop="'categories.' + index" :rules="rules.discountAmount">
								<el-checkbox v-model="item.discountChecked">{{ item.categoryName }}{{ item.status ? '' : '(已停用)' }}</el-checkbox>
								&nbsp;&nbsp;
								<el-input v-model="item.discountAmount" placeholder="请输入" :disabled="!item.discountChecked" max="3" class="discount-input">
									<template slot="append">
										折
									</template>
								</el-input>
							</el-form-item>
						</div>
					</el-collapse-transition>
				</el-form-item>
				<el-form-item label="会员生日积分" prop="right.point" :rules="rules.point">
					<el-switch v-model="form.right.point" active-color="#13ce66" inactive-color="#ff4949" />
					<el-collapse-transition>
						<div v-if="form.right.point">
							<el-form-item v-for="(item, index) in form.categories" :key="item.categoryId" :prop="'categories.' + index" :rules="rules.pointTimes">
								<el-checkbox v-model="item.pointChecked">{{ item.categoryName }}{{ item.status ? '' : '(已停用)' }}</el-checkbox>
								&nbsp;&nbsp;
								<el-input v-model="item.pointTimes" placeholder="请输入" :disabled="!item.pointChecked" max="3" class="discount-input">
									<template slot="append">
										倍
									</template>
								</el-input>
							</el-form-item>
						</div>
					</el-collapse-transition>
				</el-form-item>
				<el-form-item label="参与门店" prop="right.shop" :rules="rules.shop">
					<el-radio v-model="form.shopRadio_extra" :label="1">全部门店</el-radio>
					<br />

					<el-radio v-model="form.shopRadio_extra" :label="2" style="margin-right:10px">指定门店使用</el-radio>
					<el-button :disabled="form.shopRadio_extra !== 2" @click="openShopTree(form.right.shop)">
						已选择&nbsp;
						<span style="color:red">{{ form.right.shop.length }}</span>
						&nbsp;家门店
					</el-button>
				</el-form-item>
				<el-form-item label="赠送卡券">
					<el-table :data="form.cardCouponData" border style="width: 100%" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
						<el-table-column prop="couponId" label="批次号" width="180"></el-table-column>
						<el-table-column prop="couponName" label="卡券名称" width="180"></el-table-column>
						<el-table-column prop="couponType" label="卡券类型">
							<template slot-scope="scope">
								{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
							</template>
						</el-table-column>
						<el-table-column prop="amount" label="赠送数量" width="160">
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.amount" :min="1"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="100">
							<template slot-scope="scope">
								<el-button @click="delCardCoupon(scope.$index)" type="text" size="small">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-button type="text" @click="openDialogCardCouponTable">+ 增加卡券</el-button>
					<p>注：赠送卡券将在会员日当天0点发放，单次最多添加卡券种类不超过10种，卡券总数量不超过30张</p>
				</el-form-item>
				<el-form-item v-if="superData.status == 1" label="超级会员" prop="right.superShop" :rules="rules.superShop">
					<p>注：开启后合作商户参与了活动，用户在会员日消费时候按照设置折扣优惠；</p>
					<p>积分奖励不需要合作商户参与，只要生成会员日就自动生效；</p>
					<p>此活动将默认按照与合作商户关系展示出资方；</p>
					<el-switch v-model="form.right.superSwitch" @change="superSwitchChange" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
					<div v-if="form.right.superSwitch">
						<el-radio v-model="form.superShopRadio_extra" :label="1" @change="superRadio">全部合作商户</el-radio>
						<br />
						<el-radio v-model="form.superShopRadio_extra" :label="2" style="margin-right:10px">部分合作商户</el-radio>
						<el-button :disabled="form.superShopRadio_extra !== 2" @click="openSuperShopTree()">
							已选择&nbsp;
							<span style="color:red">{{ form.right.superShopNum == 'all' ? 0 : form.right.superShop.length }}</span>
							&nbsp;家商户
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="详情介绍">
					<el-input
						v-model="form.right.detail"
						type="textarea"
						:autosize="{ minRows: 2, maxRows: 15 }"
						placeholder="请输入内容"
						maxlength="500"
						class="des-input"
						show-word-limit
					/>
					<div class="tips-info">详情介绍信息会在小程序展示给顾客</div>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" round @click="submit">保存</el-button>
					<el-button round @click="fetchData">重置</el-button>
				</el-form-item>
			</el-form>
		</div>

		<!-- 选择可用门店弹框 -->
		<DialogShopListTree ref="dialogShopListTree" title="可用门店" @emitShopIds="emitShopIds" />
		<DialogSuperShopListTree ref="dialogSuperShopListTree" title="选择合作商户" @emitSuperShopIds="emitSuperShopIds" />
		<DialogCardCouponTable
			ref="dialogCardCouponTable"
			:card-coupon-type="['cash', 'discount', 'exchange', 'cash_wx_pay', 'times', 'gift']"
			:has-checked-ids="form.hasCheckedCardCouponIds"
		/>
	</div>
</template>

<script>
import { getBirthdayBenefitConfig, saveBirthdayBenefitConfig, judgeDiscountChangeBirthday } from '@/api/marketing';
import { getAllVipCardList } from '@/api/vip';
import { querySuperMemberStatus } from '@/api/business';
import { validateDis, validateMultiple } from '@/utils/validate.js';
import DialogCardCouponTable from '@/components/DialogCardCouponTable';
export default {
	components: {
		DialogCardCouponTable
	},
	data() {
		/**
		 * 表单校验方法相关
		 */
		// 启用折扣
		const validateDiscount = (rule, value, callback) => {
			if (value) {
				let flag = false;
				this.form.categories.some(v => {
					if (v.discountChecked) {
						flag = true;
						return true;
					}
				});
				flag ? callback() : callback('启用会员生日折扣请至少设置一个折扣权益');
			} else {
				callback();
			}
		};

		// 折扣
		const validateDiscountAmount = (rule, value, callback) => {
			if (value.discountChecked) {
				this.$refs.form.clearValidate(['right.discount']);
				if (value.discountAmount == '') {
					callback(new Error('请输入折扣'));
				} else if (!validateDis(value.discountAmount)) {
					callback(new Error('请输入正整数（不大于10），或正小数（小数位不超过1位）'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		// 启用积分
		const validatePoint = (rule, value, callback) => {
			if (value) {
				let flag = false;
				this.form.categories.some(v => {
					if (v.pointChecked) {
						flag = true;
						return true;
					}
				});
				flag ? callback() : callback('启用会员生日积分请至少设置一个积分权益');
			} else {
				callback();
			}
		};

		// 积分系数
		const validatePointTimes = (rule, value, callback) => {
			if (value.pointChecked) {
				this.$refs.form.clearValidate(['right.point']);
				if (value.pointTimes == '') {
					callback(new Error('请输入积分倍数'));
				} else if (!validateMultiple(value.pointTimes)) {
					callback(new Error('请输入1.1~9.9的倍数'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		//  可使用门店
		const validateShop = (rule, value, callback) => {
			if ((this.form.right.discount || this.form.right.point) && this.form.shopRadio_extra === 2 && value.length === 0) {
				callback(new Error('请至少设置一家可使用门店'));
			} else {
				callback();
			}
		};
		//  可使用门店
		const validateSuperShop = (rule, value, callback) => {
			if ((this.form.right.discount || this.form.right.point) && this.form.superShopRadio_extra === 2 && value.length === 0) {
				callback(new Error('请至少设置一家可使用门店'));
			} else {
				callback();
			}
		};
		return {
			/**
			 * 表单校验字段相关
			 */
			rules: {
				discount: [
					{
						required: true,
						validator: validateDiscount,
						trigger: ['blur', 'change']
					}
				],
				discountAmount: [
					{
						required: true,
						validator: validateDiscountAmount,
						trigger: ['blur', 'change']
					}
				],
				point: [
					{
						required: true,
						validator: validatePoint,
						trigger: ['blur', 'change']
					}
				],
				pointTimes: [
					{
						required: true,
						validator: validatePointTimes,
						trigger: ['blur', 'change']
					}
				],
				shop: [
					{
						type: 'array',
						required: true,
						validator: validateShop,
						trigger: ['blur', 'change']
					}
				],
				superShop: [
					{
						type: 'array',
						required: true,
						validator: validateSuperShop,
						trigger: ['blur', 'change']
					}
				]
			},
			//  状态组
			loading: false,
			// 数据
			cardList: [],
			form: {
				right: {
					discount: false,
					point: false,
					shop: '',
					superSwitch: false,
					old_superSwitch: '',
					superShop: '',
					superShopNum: '',
					old_superShop: '',
					detail: '',
					mbDayId: null
				},
				categories: [],
				shopRadio_extra: 1,
				superShopRadio_extra: 1,
				openShopTreeType: null,
				// 赠送卡券
				cardCouponData: [],
				hasCheckedCardCouponIds: [] //已选择的卡券
			},
			// 超级会员
			superData: '' // status: 0:未开通 1:已开通 2:欠费停用
		};
	},
	watch: {
		form: {
			handler: function(val) {
				this.$nextTick(() => {
					// 门店
					if (val.shopRadio_extra === 1) {
						this.$refs.form.clearValidate(['right.shop']);
					} else if ((!this.form.right.discount && !this.form.right.point) || (val.shopRadio_extra === 2 && val.right.shop.length !== 0)) {
						this.$refs.form.clearValidate(['right.shop']);
					}
				});
			},
			deep: true
		}
	},
	mounted() {
		this.fetchData();
	},
	methods: {
		/**
		 * 获取数据
		 */
		// 加载页面
		async fetchData() {
			this.loading = true;
			await this.getCardList();
			this.getBirthdayConfig();
			this.querySuperMemberStatusFun();
		},

		// 获取所有卡数据
		getCardList() {
			return new Promise((resolve, reject) => {
				getAllVipCardList().then(res => {
					this.cardList = res.data;
					resolve();
				});
			});
		},

		// 获取生日配置
		getBirthdayConfig() {
			return new Promise((resolve, reject) => {
				getBirthdayBenefitConfig()
					.then(res => {
						const data = res.data;
						console.log('配置data', data);
						// 生成卡数据格式
						const categoriesArr = [];
						this.cardList.map(val => {
							const obj = {};
							obj.categoryId = val.id;
							obj.categoryName = val.categoryName;
							obj.status = val.status;
							obj.discountChecked = false;
							obj.pointChecked = false;
							obj.discountAmount = '';
							obj.pointTimes = '';
							data.categories.map(v => {
								if (obj.categoryId === v.categoryId) {
									obj.discountChecked = !!v.discountAmount;
									obj.pointChecked = !!v.pointTimes;
									obj.discountAmount = v.discountAmount ? v.discountAmount / 10 : '';
									obj.pointTimes = v.pointTimes ? v.pointTimes / 10 : '';
								}
							});
							categoriesArr.push(obj);
						});
						if (data.right.shop) {
							data.right.shop = data.right.shop.split(',');
							data.shopRadio_extra = 2;
						} else {
							data.right.shop = [];
							data.shopRadio_extra = 1;
						}
						if (data.right.superMemberJoinBusinessIds) {
							data.right.superShop = data.right.superMemberJoinBusinessIds.split(',');
							data.superShopRadio_extra = 2;
						} else {
							data.right.superShop = [];
							data.superShopRadio_extra = 1;
						}
						data.right.mbDayId = data.right.id;
						data.right.superSwitch = data.right.openSuperMember;

						data.categories = categoriesArr;
						// 赠送卡券
						data.giveCouponAndCardList.forEach(el => {
							el.couponId = el.id
							el.amount = el.giveNum
						})
						data.cardCouponData = data.giveCouponAndCardList;
						data.hasCheckedCardCouponIds = [];
						this.form = data;

						this.form.right.old_discount = data.right.discount;
						this.form.right.old_superSwitch = data.right.superSwitch;
						this.form.right.old_superShop = data.right.superShop.sort().toString();
					})
					.catch(err => {})
					.finally(() => {
						this.loading = false;
					});
			});
		},

		// 插件状态
		querySuperMemberStatusFun() {
			querySuperMemberStatus().then(res => {
				this.superData = res.data;
			});
		},

		/**
		 * 按钮组
		 */
		// 返回
		back() {
			this.$router.push({
				name: 'VipBenefitCenter'
			});
		},

		// 打开选择门店
		openShopTree() {
			this.form.right.shopTreeType = 'openShopTree';
			this.$refs.dialogShopListTree.open(this.form.right.shop);
		},
		// 选择可用门店
		emitShopIds(ids) {
			this.form.right.shop = ids;
			this.$refs.dialogShopListTree.hide();
		},
		// 超级会员-打开选择门店
		openSuperShopTree() {
			this.form.right.shopTreeType = 'openSuperShopTreeBirthday';
			this.$refs.dialogSuperShopListTree.open(this.form.right.superShop, this.form.right.mbDayId, this.form.right.shopTreeType);
		},
		// 选择可用超级会员门店
		emitSuperShopIds(prams) {
			this.form.right.superShop = prams.checkedIds;
			this.$refs.dialogSuperShopListTree.hide();
			this.form.right.superShopNum = '';
			if (prams.shopNum == 'all') {
				this.form.right.superShopNum = 'all';
				this.form.superShopRadio_extra = 1;
			}
			this.form = Object.assign({}, this.form);
		},
		superSwitchChange(e) {
			this.form.superShopRadio_extra = 1;
			this.form.right.superShop = [];
		},
		superRadio(e) {
			this.form.right.superShop = [];
		},
		// 赠送卡券
		delCardCoupon(index) {
			this.form.cardCouponData.splice(index, 1);
		},
		openDialogCardCouponTable() {
			this.form.hasCheckedCardCouponIds = [];
			this.form.cardCouponData.forEach(val => {
				this.form.hasCheckedCardCouponIds.push(val.couponId);
			});
			this.$nextTick(() => {
				this.$refs.dialogCardCouponTable.open().then(res => {
					this.form.cardCouponData = this.form.cardCouponData.concat(res);
				});
			});
		},

		// 保存
		submit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					// 过滤数据
					const data = JSON.parse(JSON.stringify(this.form));
					// 门店
					if (data.shopRadio_extra === 1) {
						data.right.shop = '';
					} else {
						data.right.shop = data.right.shop.join(',');
					}
					delete data['shopRadio_extra'];
					// 卡信息
					if (data.right.discount || data.right.point) {
						for (let i = 0; i < data.categories.length; i++) {
							if (!data.categories[i].discountChecked && !data.categories[i].pointChecked) {
								data.categories.splice(i, 1);
								i--;
							} else {
								if (!data.right.discount || !data.categories[i].discountChecked) {
									data.categories[i].discountAmount = '';
								} else {
									data.categories[i].discountAmount = this.$math.mul(data.categories[i].discountAmount, 10, 0);
								}
								if (!data.right.point || !data.categories[i].pointChecked) {
									data.categories[i].pointTimes = '';
								} else {
									data.categories[i].pointTimes = this.$math.mul(data.categories[i].pointTimes, 10, 0);
								}
								delete data.categories[i]['discountChecked'];
								delete data.categories[i]['pointChecked'];
								delete data.categories[i]['categoryName'];
								delete data.categories[i]['status'];
							}
						}
					} else {
						data.categories = [];
					}
					data.id = data.right.id;
					data.discount = data.right.discount;
					data.point = data.right.point;
					data.shop = data.right.shop;
					data.joinBusinessIds = data.right.superShop;
					data.openSuperMember = this.form.right.superSwitch;
					data.superMemberAllJoin = this.form.right.superSwitch && this.form.superShopRadio_extra == 1 ? true : false;
					data.detail = data.right.detail;
					// 赠送卡券
					data.giveCardOrCouponList = []
					data.cardCouponData.forEach(el => {
						data.giveCardOrCouponList.push({id:el.couponId,giveNum:el.amount})
					})
					delete data.right;
					console.log('保存', data);
					this.loading = true;

					// 判断修改弹窗内容
					this.judgeDialogFun(data);
				}
			});
		},
		judgeDialogFun(data) {
			let status = this.superData.status; // 1 已开通超级会员
			let changeType = '';

			let old_discount = this.form.right.old_discount; //旧开启状态
			let cur_discount = false;

			let old_superSwitch = this.form.right.old_superSwitch; //旧开启状态
			let superSwitch = this.form.right.superSwitch; //新开启状态
			let cur_superSwitch = false;

			let old_superShop = this.form.right.old_superShop; //旧商户
			let joinBusinessIds = data.joinBusinessIds.sort().toString(); //新商户
			let cur_superShop = false;

			if (status == 1) {
				judgeDiscountChangeBirthday(data).then(res => {
					cur_discount = res.data;

					if (old_superSwitch) {
						if (old_superSwitch != superSwitch) {
							cur_superSwitch = true;
						}
						if (old_superShop != joinBusinessIds) {
							cur_superShop = true;
						}

						// console.log('cur_discount--', cur_discount);
						// console.log('cur_superSwitch--', cur_superSwitch);
						// console.log('cur_superShop--', cur_superShop);
						if ((!cur_discount && cur_superSwitch) || (!cur_discount && cur_superShop)) {
							changeType = 'superShop';
							this.changeConfirm(changeType, data);
						} else if (old_discount && cur_discount && !cur_superSwitch && !cur_superShop) {
							changeType = 'discount';
							this.changeConfirm(changeType, data);
						} else if ((old_discount && cur_discount && cur_superSwitch) || (old_discount && cur_discount && cur_superShop)) {
							changeType = 'discount';
							this.changeConfirm(changeType, data);
						} else {
							this.saveMemberDayConfigFun(data);
						}
					} else {
						this.saveMemberDayConfigFun(data);
					}
				});
			} else {
				this.saveMemberDayConfigFun(data);
			}
		},
		// 修改弹窗
		changeConfirm(changeType, data) {
			let txt = '';
			if (changeType == 'discount') {
				txt = '因会员日折扣有修改，保存后已参与活动的合作商家将重新操作参与，是否保存？';
			} else if (changeType == 'superShop') {
				txt = '因修改了参与的合作商户，会导致已参与活动的合作商户自动取消参与，请谨慎操作。';
			}
			this.$confirm(txt, '提示', {
				confirmButtonText: '继续保存',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.saveMemberDayConfigFun(data);
				})
				.catch(() => {
					this.loading = false;
					return;
				});
		},
		//保存配置
		saveMemberDayConfigFun(data) {
			saveBirthdayBenefitConfig(data)
				.then(res => {
					this.$notify({
						title: '成功',
						message: '保存成功',
						type: 'success',
						duration: 2000,
						offset: 40
					});
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false;
				});
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 输入框 */
.discount-input {
	width: 160px;
}
.des-input {
	width: 600px;
}
::v-deep .el-textarea .el-input__count {
	line-height: 1;
}

/* 提示 */
.tips-info {
	line-height: 1.5;
	font-size: 12px;
	color: #909399;
}
</style>
